// pages/powerActivity/powerActivity.js
import { shareOptions } from "../../utils/access";
import { jump, getCurrentPage, getStorage, setStorage, countDown, goBack } from "../../utils/utils";
import api from "../../config/api";
import request from "../../utils/request";
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
      //用户信息 
      userHelpInfo: {},
      //倒计时时间
      day: '00',
      hour: '00',
      minute: '00',
      second: '00', 
      // 排行榜数据
      rankingList: [], 
      // 是否展开所有小区
      showAll: false,
      // 获取助力次数类型
      powerTypeList:[
        {label: '完成每日签到任务',desc: '每日签到成功，即可获得1助力值', icon: 'https://image-classify.daieco.com/kejian-quanzi/Se91FZZF7mlpd9522c84d4b20fb51171b4641845b9ef.png', state: '', type: 1},
        {label: '参与答题',desc: '每日完成答题，即可获得1助力值', icon: 'https://image-classify.daieco.com/kejian-quanzi/mMFVng5DePNsa5d87db130929d999689790e710e326d.png', state: '', type: 2},
        {label: '发布帖子',desc: '任意发布一篇帖子，即可获得1助力值', icon: 'https://image-classify.daieco.com/kejian-quanzi/ycj4l9hxtcUved4e4af5c2501ffe6cecc4f1e62c4916.png', state: '', type: 3},
        {label: '分享活动',desc: '分享活动至微信，即可获得1助力值', icon: 'https://image-classify.daieco.com/kejian-quanzi/KL1m07yje0JVc4f923ffda17d6072b797ac3c9f5ce48.png', state: '', type: 4},
      ],
      // 助力动态
      ramList:[],
      // 展示红心漂浮
      showFloat: false,
      // 弹窗
      modalText: '',
      // 今日任务是否完成
      taskComplete: false,

      // 本小区
      communityIndex: '',
      communityId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options?.inviteData) {
			setStorage('inviteData', options?.inviteData)
			console.log('分享人数据：', options.inviteData)
		}
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.modal = this.selectComponent("#modal");
    this.taskModal = this.selectComponent("#taskModal");
    if(!app.isLogin()){
      this.setData({
        modalText: '登录后才可访问'
      })
      this.modal.show()
    }else{
      if(this.modalShow){
        this.modal.show()
        this.modalShow = false
      }
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(!app.isLogin()){
      return
    }
    this.getUserHelpInfo()
    this.getHelpHands()
    this.handsTimer = setInterval(() => {
      this.getHelpHands()
    }, 5000);
    this.getCollectionStatus()
    this.getHelpDynamic()
    this.dynamicTimer = setInterval(() => {
      this.getHelpDynamic()
    }, 10000);
  },
    /**
   * 查询用户助力、登录和认证状态信息
   */
  async getUserHelpInfo(){
    let res = await request.get(api.userHelpInfo,{},{ loading:false })
    if(res.httpStatus === 200){
      this.setData({
        userHelpInfo: res.data || {}
      })
      if(!this.data.userHelpInfo.hasAuditedCommunity || !this.data.userHelpInfo.hasTargetUser){
        this.setData({
          modalText: '您所在区域暂时不支持此活动！'
        })
        if(this.modal){
          this.modal.show()
        }else{
          this.modalShow = true
        }
        return
      }
      if(res.data.activityEndTime){
        countDown(res.data.activityStartTime,res.data.activityEndTime,this)
      }
    }
  },
  /**
   * 查询助力榜数据
   */
  async getHelpHands(){
    let res = await request.get(api.helpHandsList,{},{ loading:false })
    if(res.httpStatus === 200){
      this.setData({
        rankingList: res.data || []
      })
      this.data.rankingList.forEach((item,index)=>{
        if(item.isMyCommunity){
          this.setData({
            communityId: item.communityId,
            communityIndex: index
          })
        }
      })
    }
  },
  /**
   * 获取用户获得助力次数方式的状态
   */
  async getCollectionStatus(){
    let res = await request.get(api.helpCollectionStatus,{},{ loading:false })
    let list = this.data.powerTypeList
    if(res.httpStatus === 200){
      let data = res.data || {}
      list[0].state = data.sign || ''
      list[1].state = data.answer || ''
      list[2].state = data.posting || ''
      list[3].state = data.shareEvents || ''
      let taskComplete = data.sign === 3 && data.answer === 3 && data.posting === 3 && data.shareEvents === 3
      this.setData({
        taskComplete,
        powerTypeList: list
      })
    }
  },
  /**
   * 查询助力动态
   */
  async getHelpDynamic(){
    let res = await request.get(api.helpDynamicList,{},{ loading:false })
    if(res.httpStatus === 200){
      this.setData({
        ramList: res.data || []
      })
    }
  },
  
  // 点击助力按钮
  async help(e){
    if(this.floatLoading) return
    let {communityId, communityIndex, taskComplete} = this.data
    let list = this.data.rankingList
    let userHelpInfo = this.data.userHelpInfo
    this.floatLoading = true
    if(!userHelpInfo.myHelpTimes){
      this.taskModal.show()
      this.floatLoading = false
    }else if(userHelpInfo.myHelpTimes > 0){ // 助力小区
      this.setData({
        showFloat: true
      }) 
      if(communityId){
        let res = await request.post(api.helpCommunity,{
          communityId
        }, { loading: false})
        if(res.httpStatus === 200){
          if(res.data?.progressBar && res.data?.getHelping){
            list[communityIndex].progressBar = res.data.progressBar
            list[communityIndex].getHelpingSum = res.data.getHelping
          }
           userHelpInfo.myHelpTimes = userHelpInfo.myHelpTimes - 1
           this.setData({
            rankingList: list,
            userHelpInfo
           })
           this.getUserHelpInfo()
           this.getHelpHands()
           this.getHelpDynamic()
        }
      }
      setTimeout(()=>{
        this.setData({
          showFloat: false
        }) 
        this.floatLoading = false
      },1000)
    }
  },

  /**
   * 领取
   */
  async helpReceive(e){
    if(this.loading) return 
    this.loading = true
    let type = e.currentTarget.dataset.type
    let res = await request.post(api.helpReceive, {
      type
    })
    if(res.httpStatus === 200){
      this.getUserHelpInfo()
      this.getCollectionStatus()
      wx.showToast({
        title: '助力次数+1'
      })
    }
    this.loading = false
  },

  // 跳转贡献榜
  jumpRank(e){
    let { item, type } = e.currentTarget.dataset
     let { communityId, isMyCommunity } = item
     if(!communityId) return

     if(Number(type) === 2){
      if(!isMyCommunity) return
     }
     
     jump('powerActivityRank', {
      id: communityId
     })
  },
  // 跳转活动规则
  jumpRule(){
    jump('powerActivityDesc')
  },
  // 跳转至签到页
  jumpSign(){
    setStorage('fromActivity',1)
    jump('openScreen')
  },
  // 跳转至答题页
  jumpAnswer(){
    setStorage('fromActivity',1)
    jump('test')
  },
  // 跳转至发帖页
  jumpPost(){
    jump('publish')
  },
  // 退出
  modalConfirm(){
      jump('index')
  },
  // 退出
  taskModalConfirm(){
      this.taskModal.hide()
  },

  // 展示所有小区
  handleShowAll(){
     this.setData({
       showAll: !this.data.showAll
     })
  },
  // 点击返回
  handleBack(){
    goBack()
    clearTimeout(this.timeInterval)
    clearTimeout(this.handsTimer)
    clearTimeout(this.dynamicTimer)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearTimeout(this.timeInterval)
    clearTimeout(this.handsTimer)
    clearTimeout(this.dynamicTimer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (event) {
    const userId = getStorage('userId') || ''
    let url = getCurrentPage() //当前页面url
    let shareCategory = event.from === 'button'? 2 : 1
    let params = {
      platform: 1, //1：小程序
      shareCategory, //分享类型 1：微信菜单 2：自有分享按钮
      shareType: 1, //分享方式 1：分享给朋友 2：分享到朋友圈
      url
    }
    request.post(api.helpAddActivityShare, params, {loading: false})
    return shareOptions('helpActivity',event, '助力我的小区，赢百万环保奖金', '/pages/powerActivity/powerActivity?inviteData=' + userId, 'https://image-classify.daieco.com/kejian-quanzi/kwvyg5LfmYkY7a07e81770defca857d193c085d29696.png')
  }
})